//https://www.nowcoder.com/practice/41c399fdb6004b31a6cbb047c641ed8a?tpId=196&tqId=37145&ru=/exam/oj

typedef struct ListNode ListNode;

ListNode* BuyNewnode(int i)
{
    ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
    if (newnode == NULL)
    {
        perror("malloc fail\n");
        return NULL;
    }

    newnode->next = NULL;
    newnode->val = i;
    return newnode;
}

ListNode* CreatList(int n)
{
    int i = 1;
    ListNode* phead = NULL;
    ListNode* ptail = NULL;
    phead = ptail = BuyNewnode(i++);

    while (i <= n)
    {
        ListNode* newnode = BuyNewnode(i++);
        ptail->next = newnode;
        ptail = ptail->next;
    }
    ptail->next = phead;

    return phead;
}

int ysf(int n, int m) {
    ListNode* head = CreatList(n);
    ListNode* cur = head;
    ListNode* prev = NULL;
    int count = 1;

    while (cur->next != cur)
    {
        if (count == m)
        {
            prev->next = cur->next;
            free(cur);
            cur = prev->next;
            count = 1;
        }
        else
        {
            prev = cur;
            cur = cur->next;
            count++;
        }
    }

    return cur->val;

}